<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue</title>
  <script src="./js/vue.js"></script>
</head>

<body>
  <div id="app">
    <button @click="cmp='child1'">child1</button>
    <button @click="cmp='child2'">child2</button>
    <hr>
    <!-- 动态组件,动态的根据数据来决定哪一个组件显示出来 -->
    <keep-alive>
      <component :is="cmp"></component>
    </keep-alive>
  </div>

  <script>
    // 组件
    const child1 = {
      data() {
        return {
          username: ''
        }
      },
      template: `
        <div>
          <h3>我是child1</h3>
          <input type="text" v-model='username' />
        </div>
      `,
      /* mounted() {
        console.log('child1 -- mounted')
      } */
      // 如果动态组件使用了keep-alive自带的缓存组件,则它原本的8个生命周期方法将不好用
      // 可以使用它提供针对于keep-alive所使用的生命周期方法
      // activated 当前组件被激活时触发  进入
      // deactivated 未激活时触发   离开
      activated(){
        console.log('child1 -- activated')
      },
      deactivated(){
        console.log('child1 -- deactivated')
      }
    }

    const child2 = {
      data() {
        return {
          password: ''
        }
      },
      template: `
        <div>
          <h3>我是child2</h3>
          <input type="text" v-model='password' />
        </div>
      `,
      /* mounted() {
        console.log('child2 -- mounted')
      } */
      activated(){
        console.log('child2 -- activated')
      },
      deactivated(){
        console.log('child2 -- deactivated')
      }
    }

    // 根组件
    new Vue({
      data() {
        return {
          cmp: 'child1'
        }
      },
      components: {
        child1,
        child2
      }
    }).$mount('#app')
  </script>
</body>

</html>